﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Web;

namespace AgileShare.Framework.Office.ExchangeServices
{
    public class ExChangeServiceHelper
    {
        string userMail = string.Empty;
        ExchangeService service;
        string _serverurl = string.Empty;

        public ExChangeServiceHelper(string serverurl, string usermail, ExVersion version) {
            userMail = usermail;
            _serverurl = serverurl;
            ServicePointManager.ServerCertificateValidationCallback =
            delegate(Object obj,
            X509Certificate certificate,
            X509Chain chain, SslPolicyErrors errors)
            {
                return true;
            };
            ExchangeVersion v = (ExchangeVersion)Enum.Parse(typeof(ExchangeVersion), version.ToString());
            service = new ExchangeService(v);
            service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            if (!string.IsNullOrEmpty(serverurl))
            {
                service.Url = new Uri(serverurl + "/ews/exchange.asmx");
            }
            else
            {
                service.AutodiscoverUrl(userMail);
            }
        }

        public ExChangeServiceHelper(string serverurl,string usermail,
            string domain,string adminusername,string adminuserpwd,ExVersion version)
        {
            userMail = usermail;
            _serverurl = serverurl;
            ServicePointManager.ServerCertificateValidationCallback =
            delegate(Object obj,
            X509Certificate certificate,
            X509Chain chain, SslPolicyErrors errors)
            {
                return true;
            };            
            ExchangeVersion v = (ExchangeVersion)Enum.Parse(typeof(ExchangeVersion),version.ToString());
            service = new ExchangeService(v);
            //参数是用户名,密码,域    
            service.Credentials = new WebCredentials(adminusername, adminuserpwd, domain);
            //service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;            
            if (!string.IsNullOrEmpty(serverurl))
            {
                service.Url = new Uri(serverurl+"/ews/exchange.asmx");
            }
            else
            {
                service.AutodiscoverUrl(userMail);
            }
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, usermail);
        }

        /// <summary>
        /// 获取日历
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List<CalendarEntity> GetCalendar(DateTime start, DateTime end,int pagesize) {

            List<CalendarEntity> list = new List<CalendarEntity>();

            CalendarFolder folder = CalendarFolder.Bind(service, WellKnownFolderName.Calendar);

            FindItemsResults<Appointment> findResults =
                folder.FindAppointments(new CalendarView(start,end,pagesize));

            if (findResults.Items.Count > 0)
            {
                //加载属性项,否则无法获取数据
                List<Item> LoadItems = new List<Item>();
                foreach (Appointment item in findResults.Items)
                {
                    LoadItems.Add(item);
                }
                service.LoadPropertiesForItems(
                    LoadItems,
                    PropertySet.FirstClassProperties);

                foreach (Item item in LoadItems)
                {
                    var appoint = findResults.Items.First(o => o.Id == item.Id);
                    CalendarEntity listitem = new CalendarEntity();
                    listitem.Subject = item.Subject;
                    listitem.DateTimeSent = item.DateTimeSent;
                    listitem.Body = HttpUtility.HtmlDecode(item.Body.Text);
                    listitem.DisplayTo = item.DisplayTo;
                    listitem.Start = appoint.Start;
                    listitem.End = appoint.End;
                    listitem.Location = appoint.Location;
                    listitem.Duration = appoint.Duration;
                    listitem.WebClientReadFormQueryString =
                        HttpUtility.UrlEncode(string.Format("{0}/owa/{1}",this._serverurl,appoint.WebClientReadFormQueryString));
                    listitem.WebClientEditFormQueryString =
                        HttpUtility.UrlEncode(string.Format("{0}/owa/{1}", this._serverurl, appoint.WebClientEditFormQueryString));
                    list.Add(listitem);
                }
            }
            return list;
        }
        /// <summary>
        /// 获取未读邮件总数
        /// </summary>
        /// <returns></returns>
        public Int32 GetUnreadMailCount() {
            int unRead = Folder.Bind(service, WellKnownFolderName.Inbox).UnreadCount;
            return unRead;
        }
    }
}
